package com.example.edu.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.base.handler.Exception.GuliException;
import com.example.edu.entity.Subject;
import com.example.edu.entity.excel.SubjectData;
import com.example.edu.service.SubjectService;

import java.util.Map;

public class SubjectEventListener extends AnalysisEventListener<SubjectData> {

    public SubjectService subjectService;
    public SubjectEventListener(SubjectService subjectService){
        this.subjectService=subjectService;
    }
    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        if(subjectData==null){
            throw new GuliException(20001,"添加失败");
        }
        //处理一级分类
        Subject subjectone = existOneSubject(subjectService,subjectData.getOneSubjectName());
        if(subjectone==null){
            subjectone=new Subject();
            subjectone.setTitle(subjectData.getOneSubjectName());
            subjectone.setParentId("0");
            subjectService.save(subjectone);
        }
        //获取一级分类id值
        String pid = subjectone.getId();
        //处理二级分类
        Subject subjecttwo = existTwoSubject(subjectService,subjectData.getTwoSubjectName(),pid);
        if(subjecttwo==null){
            Subject sub=new Subject();
            sub.setTitle(subjectData.getTwoSubjectName());
            sub.setParentId(pid);
            subjectService.save(sub);
        }
    }

    //读取excel表头信息
    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        System.out.println("表头信息："+headMap);
    }

    //    判断一级分类是否为存在
    private Subject existOneSubject(SubjectService subjectService,String name){
        QueryWrapper<Subject> queryWrapper=new QueryWrapper();
        queryWrapper.eq("title",name);
        queryWrapper.eq("parent_id",0);
        return subjectService.getOne(queryWrapper);
    }
    //    判断二级分类是否存在
    private Subject existTwoSubject(SubjectService subjectService,String name,String pid){
        QueryWrapper<Subject> queryWrapper=new QueryWrapper();
        queryWrapper.eq("title",name);
        queryWrapper.eq("parent_id",pid);
        return subjectService.getOne(queryWrapper);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
